<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline" v-if="permissionStore.hasPermisson('bygjzdlb.cx')">
            <a-form-item label="登记单号">
              <!-- <a-select popup-container="html"  :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                                    class="bacClass" v-model="pageData.dropDownData" :filter-option="false" allow-search
                                    allow-clear @focus="focusSel('carryNumber')">
                                    <a-option v-for="item in pageData.nameList" :value="item['carryNumber']">{{
                                    item['carryNumber'] }}</a-option>
                                </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="pageData.dropDownData"
                @press-enter="huiche"></a-input>
            </a-form-item>
            <a-form-item label="搬运工">
              <!-- <a-select popup-container="html"  :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                                    class="bacClass" v-model="pageData.dropDownData1" :filter-option="false"
                                    allow-search allow-clear @focus="focusSel('staffName')">
                                    <a-option v-for="item in pageData.nameList1" :value="item['staffName']">{{
                                        item['staffName']
                                    }}</a-option>
                                </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="pageData.dropDownData1"
                @press-enter="huiche"></a-input>
            </a-form-item>
            <a-form-item label="登记日期">
              <!-- <a-date-picker  popup-container="html"  :style="{ width: '150px' }"  class="bacClass" v-model="pageData.registerTime" @press-enter="huiche" />至
                            <a-date-picker  popup-container="html"  :style="{ width: '150px' }" class="bacClass" v-model="pageData.registerTime2" @press-enter="huiche" /> -->
              <a-range-picker  popup-container="html"  class="bacClass" @select="onSelect" style="width: 200px" @clear="onClear" />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar class="gesture" :items="pageData.btnList" @add="addHandler" @del="deleteHandler"
            @select="selectHandler" @export="exports" @cel="toVoid" style="float: right">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-space style="float: right; z-index: 9999"> </a-space>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%" :defaultColDef="defaultColDef"
          class="ag-theme-alpine" :rowData="table.dataList" :localeText="localeText1" :columnDefs="tc"></AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
      style="justify-content: center" />
    <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" :mask-closable="false" :width="400"
      unmount-on-close popup-container=".arco-tabs-content" placement="bottom" :height="pageData.rHeight"
      :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" @ok="sideOk" @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div style="height: 50px">
        <a-form size="small" :model="dataForm" layout="inline" ref="formRef">
          <!-- <a-form-item label="登记日期">
                        <a-date-picker  popup-container="html"  class="bacClass" v-model="dataForm.registerTime" />
                    </a-form-item> -->
          <!-- <a-form-item label="登记单号">
                        <a-select popup-container="html"  :style="{ width: '200px' }" :loading="loading" @search="handleSearch" class="bacClass"
                            v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                        </a-select>
                    </a-form-item> -->
          <CorporateSectorCascader ref="cascaderRef" :configCascader="configCascader" @changeCascader="changeCascader" />
        </a-form>
      </div>
      <div style="height: calc(100% - 50px)">
        <a-space style="margin-bottom: 10px">
          <a-button type="primary" @click="addLine" size="mini">新增</a-button>
          <a-button type="primary" @click="delLine" size="mini">删除</a-button>
        </a-space>
        <a-space style="margin-bottom: 10px; font-size: 16px; color: red">
          <span>总重量：{{ pageData.totalWeight }}</span>
          <span style="margin: 0 10px">总条数：{{ pageData.totalNumber }}</span>
          <span>总计件工资：{{ pageData.totalWages }}</span>
        </a-space>
        <a-table stripe :bordered="true" :columns="tableColumns1" size="mini"
          :row-selection="{ showCheckedAll: true, width: 50 }" v-model:selected-keys="s" :loading="table.tableLoading"
          :data="pageData.list" rowKey="id">
          <template #weight="{ record }">
            <div style="width: 100%">
              <a-input-number class="input-demo bacClass" :min="0" :max="10000000000000" v-model="record.weight"
                :disabled="record.number != 0 && record.number != null && record.number != undefined
                  " @change="calculateSalary(record)" :precision="2" />
            </div>
          </template>
          <template #number="{ record }">
            <div style="width: 100%">
              <a-input-number v-model="record.number" class="input-demo bacClass" :min="0" :max="10000000000000"
                :disabled="record.weight != 0 && record.weight != null && record.weight != undefined
                  " @change="calculateSalary(record)" :precision="2" />
            </div>
          </template>
          <template #staffName="{ record }">
            <div style="width: 100%">
              <a-input v-model="record.staffName" style="background-color: aqua; cursor: pointer" readonly
                @click="openStaff(record)" />
            </div>
          </template>
          <template #carryProjectName="{ record }">
            <div style="width: 100%">
              <a-select popup-container="html"  :loading="loading" @search="handleSearchCpj" class="bacClass" v-model="record.carryProjectName"
                :filter-option="false" allow-search allow-clear @focus="focusSelCpj"
                @change="changeCpj(record, record.carryProjectName)">
                <a-option v-for="item in pageData.cpjList" :value="item.transportName">{{
                  item.transportName
                }}</a-option>
              </a-select>
            </div>
          </template>
        </a-table>

        <!--   <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                    :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="pageData.addDataList"
                    :localeText="localeText1" :columnDefs="tc1"></AgGridVuesCopys> -->
      </div>
    </a-drawer>
    <a-modal v-model:visible="visible" title="选择搬运人员" @cancel="handleCancel" :draggable="true">
      <a-form :model="pageData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
        <CorporateSectorCascader ref="cascaderRef1" :configCascader="configCascader" @changeCascader="changeCascader1" />
        <a-form-item label="搬运人员">
          <a-select popup-container="html"  class="bacClass" v-model="pageData.dismantlingSheetNumber" multiple @focus="getPersonnel"
            style="width:250px;">
            <a-option v-for="(item, index) in pageData.dismantlingSheetNumberList" :value="item['id']">
              {{ item.name }}
            </a-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button type="primary" size="small" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs, nextTick } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import MyTable from '@/components/MyTable'
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
// 引入

import { localeText } from '@/api/aggridZw'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'

interface DismantlingPayroll {
  id: any
  serialNumber: any
  carryNumber: string
  remark: string
  createName: string
  createTime: string
  updateName: string
  updateTime: string
  firmGroupId: any
  carryType: string
  carryProjectName: string
  price: any
  weight: any
  number: any
  staffId: string
  pieceMoney: any
  staffName: string
  company: string
  firmGroupsId: any
  firmId: any
  firm: any
  departmentId: any
  department: any
}

export default {
  name: 'HandlingList',

  setup() {
    const total = ref(0)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      page.value = val
      doRefresh()
    }
    function change1(val: any) {
      size.value = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)
    let cascaderRef = ref('')
    let configCascader = ref<{}>({
      corporateWidth: '250px', //公司宽度
      sectorWidth: '250px', //部门宽度
      corporateRquired: true, //公司是否必填
      sectorRquired: true, //部门是否必填
      size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
      corporateName: '公司', //公司label
      sectorName: '部门', //部门label
    })
    const changeCascader = (data: any) => {
      const { corporateId, sectorId, sectorLabel, corporateLabel } = data
      dataForm.firmId = corporateId
      dataForm.firm = corporateLabel
      dataForm.departmentId = sectorId
      dataForm.department = sectorLabel
    }
    let cascaderRef1 = ref('')
    const changeCascader1 = (data: any) => {
      const { corporateId, sectorId } = data
      pageData.firmId = corporateId
      pageData.departmentId = sectorId
    }
    function doRefresh() {
      pageData.pageLoading = true
      post({
        url: 'pieceData/CarryPiece/findCarryPiece?page=' + page.value + '&limit=' + size.value,
        data: {
          deleteState: '0',
          carryNumber: pageData.dropDownData,
          staffName: pageData.dropDownData1,
          registerTime: pageData.registerTime,
          registerTime2: pageData.registerTime2,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.items)
            // 查询方法改
            gridOption.value.setRowData(data.items)
            total.value = data.page.total
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const selectedRowKeys1 = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '公司',
        key: 'firm',
        dataIndex: 'firm',
        width: 150,
      },
      {
        title: '登记单号',
        key: 'carryNumber',
        dataIndex: 'carryNumber',
        width: 150,
      },
      {
        title: '计件日期',
        key: 'pieceDate',
        dataIndex: 'pieceDate',
        width: 150,
      },
      {
        title: '单位',
        key: 'unit',
        dataIndex: 'unit',
        width: 150,
      },
      {
        title: '搬运项目名称',
        key: 'carryProjectName',
        dataIndex: 'carryProjectName',
        width: 150,
      },
      {
        title: '单价',
        key: 'price',
        dataIndex: 'price',
        width: 150,
      },
      {
        title: '搬运员工',
        key: 'staffName',
        dataIndex: 'staffName',
        width: 150,
      },
      {
        title: '计件工资',
        key: 'pieceMoney',
        dataIndex: 'pieceMoney',
        width: 150,
      },

      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 200,
      },
      {
        title: '作废状态',
        key: 'toState',
        dataIndex: 'toState',
        width: 100,
        fixed: 'right',
        slotName: 'toState',
      },
      {
        title: '操作',
        key: 'id',
        slotName: 'act',
        width: 100,
        fixed: 'right',
      },
    ])

    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 120
        obj['cellRenderer'] = {
          // template: `<a-tag color="#ff7d00" v-if="isEdit" class="gesture" @click="a" v-if="e">修改</a-tag>`,
          template: `<el-button style="color:#165dff;" link  v-if="isEdit && e"  @click="a">修改</el-button>`,

          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            let isEdit = permissionStore.hasPermisson('bygjzdlb.xg')
            return {
              a,
              e: props.params.data.toState == 0,
              isEdit,
            }
          },
        }
      }
      if (o.slotName === 'toState') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 120
        obj['cellRenderer'] = {
          template: `<a-space>
            <el-tag  type="info" v-if="params.data.toState==1">{{val}}</el-tag>
            <el-tag  type="success" v-else>{{val}}</el-tag>
          </a-space>`,

          
          setup(props: any) {
            let val = ref()
            if (props.params.data.toState == 0) {
              val.value = '未作废'
            } else {
              val.value = '已作废'
            }

            return {
              val,
            }
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)

    const tableColumns1 = useTableColumn([
      {
        title: '序号',
        key: 'serialNumber',
        dataIndex: 'serialNumber',
        width: 150,
      },

      {
        title: '搬运项目名称',
        key: 'carryProjectName',
        dataIndex: 'carryProjectName',
        width: 150,
        slotName: 'carryProjectName',
      },
      {
        title: '单价',
        key: 'price',
        dataIndex: 'price',
        width: 150,
      },
      {
        title: '重量',
        key: 'weight',
        dataIndex: 'weight',
        width: 150,
        slotName: 'weight',
      },
      {
        title: '条数',
        key: 'number',
        dataIndex: 'number',
        width: 150,
        slotName: 'number',
      },
      {
        title: '搬运员工',
        key: 'staffName',
        dataIndex: 'staffName',
        width: 150,
        slotName: 'staffName',
      },
      {
        title: '计件工资',
        key: 'pieceMoney',
        dataIndex: 'pieceMoney',
        width: 150,
        slotName: 'pieceMoney',
      },
    ])

    let tc1: any[] = tableColumns1.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'

        obj['cellRenderer'] = {
          template: `<div color="#ff7d00" class="gesture" @click="a"></div>`,
          setup(props: any) {
            const a = () => {
              if (
                props.params.data.staffId != '' &&
                props.params.data.staffId != null &&
                props.params.data.staffId != undefined
              ) {
                props.params.data
                getFirmGroup()
                getPersonnel()
              }

              visible.value = true
            }
            return {
              a,
            }
          },
        }
      }

      return obj
    })

    tc1 = a.concat(tc1)
    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      nameList: []
      pageLoading: boolean
      typeList: []
      dropDownData1: any
      rHeight: any
      btnList: any[]
      isEdit: boolean
      dismantlingSheetNumber: any[]
      dismantlingSheetNumberList: any[]
      addDataList: any[]
      list: any[]
      company: any
      firmList1: any[]
      firmList: any[]
      bmList: any[]
      bmList1: any[]
      bumen: any
      cpjList: any[]
      totalWages: any
      totalNumber: any
      totalWeight: any
      registerTime: any
      registerTime2: any
      nameList1: any[]
      departmentId: any
      firmId: any
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增拆纱工资单',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      dismantlingSheetNumber: [],
      dismantlingSheetNumberList: [],
      addDataList: [],
      list: [],
      company: '',
      firmList1: [],
      firmList: [],
      bmList: [],
      bmList1: [],
      bumen: null,
      cpjList: [],
      totalWages: 0,
      totalNumber: 0,
      totalWeight: 0,
      registerTime: '',
      registerTime2: '',
      nameList1: [],
      departmentId: '',
      firmId: '',
    })

    interface gcType {
      id: any
      company: any
    }
    let field = ''
    //下拉框得到焦点
    const focusSel = (val: any) => {
      field = val
      let ob = {}
      ob[field] = ''
      selCxAll(ob)
    }
    //下拉数据
    const options = ref<any>(pageData.nameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = { field: value }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.nameList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: 'pieceData/CarryPiece/findCarryPiece2',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          if (field == 'carryNumber') {
            pageData.nameList = data.items
          } else if (field == 'staffName') {
            pageData.nameList1 = data.items
          }
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    //下拉框得到焦点
    const focusSelCpj = () => {
      selCxAllCpj({ transportName: '' })
    }
    //下拉数据
    const optionsCpj = ref<any>(pageData.cpjList)
    const handleSearchCpj = (value: any) => {
      if (value) {
        const ob = { transportName: value }
        loading.value = true
        selCxAllCpj(ob)
        optionsCpj.value = pageData.cpjList
        loading.value = false
      } else {
        optionsCpj.value = []
      }
    }

    //下拉框查询
    function selCxAllCpj(val: any) {
      post({
        url: 'pieceData/transportPrice/getList',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.cpjList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      // // 切换tap到本页面执行的方法
      // emitter.on("BrandInfo", () => {
      //     // selCxAll1({});
      //     doRefresh();
      // });
      pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
      //弹出层的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight - 100
      }
      window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 100
        }
      })
    })
    let cxbl = ''
    //查询
    const selectHandler = () => {
      pagination.page = 1
      cxbl = pageData.dropDownData
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })
    const addHandler = () => {
      pageData.list = []
      foucusUseFrim(1)
      for (var key in dataForm) {
        if (key == 'id' || key == 'firmGroupId' || key == 'firmGroupsId') {
          dataForm[key] = null
        } else if (
          key == 'serialNumber' ||
          key == 'price' ||
          key == 'weight' ||
          key == 'number' ||
          key == 'pieceMoney'
        ) {
          dataForm[key] = 0
        } else {
          dataForm[key] = ''
        }
      }
      calculatedField()

      pageData.showAdd = true
      pageData.sideTitle = '新增搬运件资单'
    }
    let curobj = null
    const editHandler = (record: DismantlingPayroll) => {
      curobj = record
      foucusUseFrim(1)
      //查这个单号所有的数据
      post({
        url: 'pieceData/CarryPiece/findCarryPiece?page=' + page.value + '&limit=' + size.value,
        data: {
          deleteState: '0',
          carryNumber: record.carryNumber,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            pageData.list = data.items
            for (var key in record) {
              dataForm[key] = record[key]
            }
            calculatedField()
            pageData.sideTitle = '修改搬运件资单'
            pageData.showAdd = true
            nextTick(() => {
              let data = {
                sectorId: record.departmentId,
                sectorLabel: record.department,
                corporateId: record.firmId,
                corporateLabel: record.firm,
              }
              cascaderRef.value.parentComponent(data)
            })
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
    const dataForm = reactive<DismantlingPayroll>({
      id: null,
      remark: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      serialNumber: 0,
      carryNumber: '',
      firmGroupId: null,
      carryType: '',
      carryProjectName: '',
      price: 0,
      weight: 0,
      number: 0,
      staffId: '',
      pieceMoney: 0,
      staffName: '',
      company: '',
      firmGroupsId: null,
      firmId: '',
      firm: '',
      departmentId: '',
      department: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
    }

    let formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          if (pageData.list.length == 0) {
            Message.warning({
              content: '请新增一条搬运件资单列表！',
              duration: 5000,
            })
            return
          }
          pageData.list.forEach(function (o: any) {
            if ((o['id'] + '').indexOf('add') != -1) {
              o['id'] = null
            }
          })
          let flag = false
          pageData.list.forEach(function (o: any) {
            if (
              o['staffName'] == '' ||
              o['staffName'] == undefined ||
              o['staffName'] == null ||
              o['carryProjectName'] == '' ||
              o['carryProjectName'] == undefined ||
              o['carryProjectName'] == null
            ) {
              flag = true
            }

            o['pieceMoney'] = parseFloat(o['pieceMoney'])
            o['registerTime'] = dataForm['registerTime']
            o['firmId'] = dataForm['firmId']
            o['firm'] = dataForm['firm']
            o['department'] = dataForm['department']
            o['departmentId'] = dataForm['departmentId']
            if (
              (o['weight'] == 0 ||
                o['weight'] == undefined ||
                o['weight'] == null ||
                o['weight'] == '') &&
              (o['number'] == 0 ||
                o['number'] == undefined ||
                o['number'] == null ||
                o['number'] == '')
            ) {
              flag = true
            }
          })
          if (flag) {
            Message.warning({
              content: '每一行的条数、重量都要必填一个,员工、搬运项目必选',
              duration: 5000,
            })
            return
          }
          pageData.pageLoading = true
          if (pageData.sideTitle === '新增搬运件资单') {
            post({
              url: 'pieceData/CarryPiece/insert',
              data: pageData.list,
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false

                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
                doRefresh()
                pageData.list = []
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          } else {
            post({
              url: 'pieceData/CarryPiece/update',
              data: pageData.list,
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false

                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
                doRefresh()
                pageData.list = []
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          }
        }
      })
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      let list = gridOption.value.getSelectedRows()
      list.forEach(function (o: any) {
        o['deleteState'] = 1
      })
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true
          post({
            url: 'pieceData/CarryPiece/update',
            data: list,
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '删除失败',
                  duration: 5000,
                })
              }
            })
            .finally(() => {
              pageData.pageLoading = false
            })
        },
      })
    }

    //导出
    const exports = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        let idList: any = []
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          idList.push(o['id'])
        })
        //将表头拼接出来
        let head =
          '<th>登记单号</th><th>搬运项目名称</th><th>单价</th><th>搬运员工</th><th>计件工资</th><th>登记日期</th><th>作废状态</th>' +
          '<th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return (
            gridOption.value
              .getSelectedRows()
              .map((o: any) => {
                return o.id
              })
              .indexOf(o['id']) !== -1
          )
        })
        let body = ''
        nowRow.forEach(function (o) {
          body += '<tr><td>' + o['carryNumber'] + '</td>'
          body += '<td>' + o['carryProjectName'] + '</td>'
          body += '<td>' + o['price'] + '</td>'
          body += '<td>' + o['staffName'] + '</td>'
          body += '<td>' + o['pieceMoney'] + '</td>'
          body += '<td>' + o['registerTime'] + '</td>'
          body += '<td>' + (o['toState'] == 0 ? '未作废' : '已作废') + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '搬运件资单', body)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }

    //打开单号弹窗
    const visible = ref(false)
    const handleOk = () => {
      if (pageData.dismantlingSheetNumber.length == 0) {
        Message.error({
          content: '请选择搬运员工',
          duration: 5000,
        })
        return
      }
      //以逗号形式将员工名称和员工id拼接
      recordOb['staffId'] = pageData.dismantlingSheetNumber.join(',')
      let list = pageData.dismantlingSheetNumberList.filter(function (o: any) {
        return pageData.dismantlingSheetNumber.includes(o['id'])
      })
      if (list.length > 0) {
        for (var i = 0; i < list.length; i++) {
          if (i == 0) {
            console.log(list[i])
            recordOb['empCode'] = list[i].code
            recordOb['staffName'] = list[i].name
          } else {
            recordOb['staffName'] += ',' + list[i].name
            recordOb['empCode'] += ',' + list[i].code
          }
        }
      }
      visible.value = false
    }
    const handleCancel = () => {
      visible.value = false
    }
    const localeText1: any = ref(localeText)
    let c = 0
    //成分添加一行 点击新增按钮
    const addLine = () => {
      //在这个数组前面添加一行
      pageData.list.unshift({
        id: 'add' + c++,
        carryProjectName: '',
        price: 0,
        weight: 0,
        number: 0,
        'staffName ': '',
        staffId: null,
        pieceMoney: 0,
      })
    }
    //子表 删除
    const delLine = () => {
      if (selectedRowKeys1.selectedRowKeys.value.length === 0) {
        Message.error({
          content: '请先勾选',
          duration: 5000,
        })
        return
      }
      pageData['list'] = pageData['list'].filter(function (o: any) {
        return selectedRowKeys1.selectedRowKeys.value.indexOf(o['id']) === -1
      })
    }
    let recordOb = {}
    //打开员工弹窗
    const openStaff = (record: any) => {
      pageData.company = ''
      pageData.dismantlingSheetNumber = []
      recordOb = record
      // pageData.dismantlingSheetNumber= record.staffId.split(',')
      visible.value = true
    }
    //拿到所有公司
    const foucusUseFrim = (num: any) => {
      let ob = {}
      if (num == 1) {
        ob['firmName'] = ''
        ob['department'] = ''
        // ob['firmTypeId'] = ""
      }
      if (num == 2) {
        if (dataForm.firmGroupsId !== '' && dataForm.firmGroupsId !== undefined) {
          let list = pageData.firmList.filter(function (o: any) {
            return o['id'] == dataForm.firmGroupsId
          })
          ob['firmName'] = list[0]['firmName']
          // dataForm.firmGroupsId = list[0]['typeName'] ? list[0]['typeName'] + '-' + list[0]['firmName'] : list[0]['firmName']
          ob['department'] = list[0]['department']
          ob['firmTypeId'] = list[0]['firmTypeId']
        } else {
          Message.warning({
            content: '请先选择公司',
            duration: 5000,
          })
        }
      }

      // getFrimList(ob, num)
    }
    const options2 = ref(pageData.firmList)
    const loading2 = ref(false)

    const handleSearch2 = (value: any) => {
      if (value) {
        loading2.value = true

        options2.value = pageData.firmList
        loading2.value = false
      } else {
        options2.value = []
      }
    }
    // function getFrimList(ob: any, nums: any) {
    //   post({
    //     url: 'org/firmGroup/getFirmInfoByMap',
    //     data: ob,
    //   }).then((result: any) => {
    //     if (result.code === 200) {
    //       if (nums == 1) {
    //         pageData.firmList = result.data
    //       }
    //       if (nums == 2) {
    //         pageData.bmList = result.data
    //       }
    //     } else {
    //       Message.error(result.message)
    //     }
    //   })
    // }
    //公司改变 部门为=空
    const changeGs = (num: any) => {
      if (num == 1) {
        dataForm.firmGroupId = ''
      } else {
        dataForm.firmGroupId = ''
      }
    }
    // 指派人员接口
    function getPersonnel() {
      //查所有的员工
      post({
        url: 'org/hrEmployee/getList',
        data: {
          company_id: pageData.firmId,
          deleteState: 0,
          department_id: pageData.departmentId,
          obsoleteState: 0,
        },
      }).then((res) => {
        if (res.code == 200) {
          pageData.dismantlingSheetNumberList = res.data
        } else {
          Message.error({
            content: res['message'],
            duration: 5000,
          })
        }
      })
    }
    //获取公司部门组列表
    const getFirmGroup = () => {
      get({
        url: '/org/firmGroup/getTreeFirmGroup',
      }).then(({ code, data }) => {
        if (code === 200) {
          pageData.firmList = data
        }
      })
    }
    //计算计件工资
    const calculateSalary = (record: any) => {
      if (record.number != 0 && record.number != undefined && record.number != null) {
        record.pieceMoney = (record.number * parseFloat(record.price)).toFixed(2)
      }
      if (record.weight != 0 && record.weight != undefined && record.weight != null) {
        record.pieceMoney = (record.weight * parseFloat(record.price)).toFixed(2)
      }
      calculatedField()
    }
    //搬运项目名下拉框改变 单价带出
    const changeCpj = (record: any, val: any) => {
      let list = pageData.cpjList.filter(function (o: any) {
        return o['transportName'] == val
      })
      if (list.length > 0) {
        record.price = list[0]['price']
      }
      calculateSalary(record)
    }
    //计算总重量/条数/计件工资
    function calculatedField() {
      pageData.totalWeight = 0
      pageData.totalNumber = 0
      pageData.totalWages = 0
      pageData.list.forEach(function (o: any) {
        if (o['weight'] != undefined && o['weight'] != null) {
          pageData.totalWeight += parseFloat(o['weight'])
        }
        if (o['number'] != undefined && o['number'] != null) {
          pageData.totalNumber += parseFloat(o['number'])
        }
        if (o['pieceMoney'] != undefined && o['pieceMoney'] != null) {
          pageData.totalWages += parseFloat(o['pieceMoney'])
        }
      })
    }
    //作废
    const toVoid = () => {
      if (gridOption.value.getSelectedRows().length == 0) {
        Message.warning({
          content: '请勾选一条数据',
          duration: 5000,
        })
        return
      }
      let rowData = gridOption.value.getSelectedRows()
      rowData.forEach(function (o: any) {
        o['toState'] = 1
      })
      post({
        url: 'pieceData/CarryPiece/update',
        data: rowData,
      })
        .then((res: any) => {
          if (res.code === 200) {
            formRef.value?.resetFields()
            pageData.showAdd = false

            Message.success({
              content: '修改成功',
              duration: 5000,
            })
          } else {
            Message.error({
              content: res.message,
              duration: 5000,
            })
          }
          doRefresh()
        })
        .finally(() => {
          pageData.pageLoading = false
        })
    }
    const huiche = () => {
      doRefresh()
    }
    const onSelect = (dateString: any) => {
      pageData.registerTime = dateString[0]
      pageData.registerTime2 = dateString[1]
    }
    const onClear = () => {
      pageData.registerTime = ''
      pageData.registerTime2 = ''
    }
    //  :items="['查询', '新增', '删除', '导出', '作废']"
    const permissionStore = usePermission()
    if (permissionStore.hasPermisson('bygjzdlb.cx')) {
      pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('bygjzdlb.xz')) {
      pageData.btnList.push('新增')
    }
    if (permissionStore.hasPermisson('bygjzdlb.sc')) {
      pageData.btnList.push('删除')
    }
    if (permissionStore.hasPermisson('bygjzdlb.dc')) {
      pageData.btnList.push('导出')
    }
    if (permissionStore.hasPermisson('bygjzdlb.zf')) {
      pageData.btnList.push('作废')
    }
    return {
      onSelect,
      onClear,
      huiche,
      toVoid,
      changeCpj,
      focusSelCpj,
      handleSearchCpj,
      optionsCpj,
      calculateSalary,
      getFirmGroup,
      options2,
      loading2,
      handleSearch2,
      foucusUseFrim,
      changeGs,
      getPersonnel,
      cascaderRef,
      configCascader,
      changeCascader,
      cascaderRef1,
      changeCascader1,
      openStaff,
      addLine,
      delLine,
      visible,
      handleOk,
      handleCancel,
      localeText1,
      defaultColDef,
      tc,
      tc1,
      total,
      PageSize,
      change1,
      page,
      size,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      exports,
      options,
      loading,
      handleSearch,
      focusSel,
      headerShow,
      gridReady,
      s: selectedRowKeys1.selectedRowKeys,
      tableColumns1,
      permissionStore,
    }
  },
  components: { Toolbar, PageTabelLayout, CorporateSectorCascader },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>